/**
 * @author YJSYS
 *
 */

package com.qd.extcam;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import android.os.AsyncTask;
import android.util.Log;

public class ServerAsyncTask extends AsyncTask<Void, Void, String> {
	private ExtCamActivity activity;
	public static int SERVER_PORT = 8988;
	/* For Client Connection Valid Check */
	ArrayList<ClientJob> jobList = new ArrayList<ClientJob>();

	/** 클라이언트와 통신을 위한 서버 소켓을 생성하고 클라이언트 작업 쓰레드를 생성한다.
	 * @param activity 메인 Activity
	 */
	public ServerAsyncTask(ExtCamActivity activity) {
		this.activity = activity;
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected String doInBackground(Void... params) {
		try {
			ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
			Log.e(ExtCamActivity.TAG, "Server: Socket opened");
			while (ExtCamActivity.running) {
				Socket client = serverSocket.accept();
				ClientJob cj = new ClientJob(activity, client, this);
				cj.start();
				jobList.add(cj);
			}
			serverSocket.close();
			return null;
		} catch (IOException e) {
			Log.e(ExtCamActivity.TAG, e.getMessage());
			return null;
		}
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(String result) {
		if (jobList.size() > 0) {
			for (int i=0; i<jobList.size(); i++) {
				ClientJob job = jobList.get(i);
				job.running = false;
			}
			jobList.clear();
		}
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onPreExecute()
	 */
	@Override
	protected void onPreExecute() {
	}
}
